/* eslint-disable import/no-duplicates */
/* eslint-disable import/no-webpack-loader-syntax */
/* eslint-disable new-cap */
// import * as monaco from 'monaco-editor-core'
import editorWorker from 'worker-loader!monaco-editor-core/esm/vs/editor/editor.worker.js'
import vueWorker from 'worker-loader!../vue.worker.js'

import { editor, languages } from 'monaco-editor-core'
import * as volar from '@volar/monaco'
// import editorWorker from 'monaco-editor-core/esm/vs/editor/editor.worker.js'
// import vueWorker from 'monaco-volar/dist/worker/vue.worker.js'

function loadMonacoEnv () {
  console.log('editorWorker', editorWorker)
  // console.log('vueWorker', vueWorker)
  self.MonacoEnvironment = {
    async getWorker (_, label) {
      if (label === 'vue') {
        // return new Worker('/vue.worker.js')
        return new vueWorker()
        // return monaco.editor.createWebWorker(vueWorker)
      }
      // return new Worker(editorWorker)
      return new editorWorker()
      // return monaco.editor.createWebWorker(editorWorker)
    }
  }
}

function setupMonacoEnv (takeoverMode = false) {
  let initialized = false

  languages.register({ id: 'vue', extensions: ['.vue'] })
  languages.onLanguage('vue', setup)

  if (takeoverMode) {
    languages.onLanguage('javascript', setup)
    languages.onLanguage('typescript', setup)
    languages.onLanguage('javascriptreact', setup)
    languages.onLanguage('typescriptreact', setup)
    languages.onLanguage('json', setup)
  }

  async function setup () {
    if (initialized) {
      return
    }
    initialized = true

    if (self.MonacoEnvironment === null || self.MonacoEnvironment === undefined) {
      self.MonacoEnvironment = {}
    }

    if (self.MonacoEnvironment.getWorker === null || self.MonacoEnvironment.getWorker === undefined) {
      self.MonacoEnvironment.getWorker = () => new editorWorker()
    }

    const getWorker = self.MonacoEnvironment.getWorker

    self.MonacoEnvironment.getWorker = (_, label) => {
      if (label === 'vue') {
        return new vueWorker()
      }
      return getWorker()
    }

    const worker = editor.createWebWorker({
      moduleId: 'vs/language/vue/vueWorker',
      label: 'vue',
      createData: {}
    })
    const languageId = takeoverMode
      ? [
          'vue',
          'javascript',
          'typescript',
          'javascriptreact',
          'typescriptreact',
          'json'
        ]
      : ['vue']
    const getSyncUris = () => editor.getModels().map((model) => model.uri)
    volar.editor.activateMarkers(
      worker,
      languageId,
      'vue',
      getSyncUris,
      editor
    )
    volar.editor.activateAutoInsertion(worker, languageId, getSyncUris, editor)
    await volar.languages.registerProvides(
      worker,
      languageId,
      getSyncUris,
      languages
    )
  }
}

export {
  loadMonacoEnv,
  setupMonacoEnv
}
